require 'socket'

def getMime(path)
  ext = File.extname(path)
  return "text/html"  if ext == ".html" or ext == ".htm"
  return "text/plain" if ext == ".txt"
  return "text/css"   if ext == ".css"
  return "image/jpeg" if ext == ".jpeg" or ext == ".jpg"
  return "image/gif"  if ext == ".gif"
  return "image/bmp"  if ext == ".bmp"
  return "text/plain" if ext == ".rb"
  return "text/xml"   if ext == ".xml" or ext == ".xsl"
  return "text/javascript" if ext == ".js"
  return "image/png" if ext == ".png"
  return "text/html"
end

def apiCall(session, command, args)
 #session.write("Command is #{command}\n")
 #args.each do |arg|
    #if not arg == "api" and not arg == ""
      #session.write("Arg: #{arg}\n")
    #end
  #end
  if command == "time"
    t = Time.now  
    session.write t.strftime("%d/%m/%Y %H:%M:%S")
  elsif command == "window"
    puts "In Windowcode"
    windowCode1 = "var nw = new Window({classname: \"mac_os_x\", blurClassName: \"blur_os_x\", title: #{arg[0]}, width: 100, height: 100});"
    windowCode2 = "nw.getContent().update('<h3><div id=\"#{arg[0]}\">#{arg[1]}</div></h3>');"
    windowCode3 = "nw.setDestroyOnClose();"
    windowCode4 = "nw.show();"
    windowCode = "#{windowCode1} #{windowCode2} #{windowCode3} #{windowCode4}"
    puts "WindowCode: #{windowCode}"
    session.write windowCode
  end
end


def serve(session)
  request = session.gets
  to_search = Regexp.new( "GET \s*(.+)\s+HTTP" )
  match = to_search.match( request )
  result = match[ 1 ]
  if result[0..3] == "/api"
    spres = result.split("/")
    command = spres[2]
    spres.delete_at(0)
    spres.delete_at(0)
    spres.delete_at(0)
    apiCall(session, command, spres)
    session.close
    return
  end
  dr = Dir.pwd + result
  dr << "/index.html" if File.directory?(dr) 
  if File.exist?(dr)
    mime = getMime(dr)
    returncode = "HTTP/1.1 200/OK\rContent-type:#{mime}\r\n\r\n"
    session.print returncode
    src = File.open(dr, "rb")
    while (not src.eof?)
      buffer = src.read(256)
      session.write(buffer)
    end
    src.close
    src = nil
  else 
    session.print "HTTP/1.1 404/Object Not Found\r\n\r\n"
  end
    session.close
end
  
server = TCPServer.new('127.0.0.1', 9191)
while (session = server.accept)
Thread.start(session) do |session| serve(session)
end
end
